<script setup>
import {computed, onMounted,onUnmounted, ref} from "vue";
import checkbox from "daisyui/components/checkbox/index.js";
import Pagination from "@/components/pagination.vue";
import UserSearchBar from "@/components/userSearchBar.vue";
import UserEditor from "@/components/userEditor.vue";
import {useUserStore} from "@/store/userStore.js";
import AddUser from "@/components/addUser.vue";
import {deleteUser} from "@/hook/userHook.js";

onMounted(async () => {
  useUserStore().search_type = '教师号'
  await useUserStore().updateTeachers(1, 5)
})
onMounted(async () => {
  useUserStore().clearUsers()
})

//分页逻辑
const handlePageChange = async (newPage) => {
  // // 这里发起API请求获取新页码数据
  await useUserStore().updateTeachers(newPage, 5)
};

// 存储选中的ID
const selectedIds = ref([]);

// 计算属性：全选状态
const selectAll = computed({
  get() {
    // 当所有项都被选中时返回true
    return selectedIds.value.length === useUserStore().users?.records?.length && useUserStore().users?.records?.length > 0;
  },
  set(value) {
    // 当全选框状态改变时更新所有选项
    if (value) {
      selectedIds.value = useUserStore().users?.records?.map(item => item.id);
    } else {
      selectedIds.value = [];
    }
  }
});

</script>

<template>
  <add-user></add-user>
  <user-search-bar class="text-base-content/50"></user-search-bar>
  <div class="overflow-x-auto text-base-content">
    <table class="table table-pin-rows table-pin-cols">
      <!-- head -->
      <thead>
      <tr>
        <th>
          <label>
            <input type="checkbox" class="checkbox" v-model="selectAll"/>
          </label>
        </th>
        <th>学号</th>
        <th>姓名</th>
        <th>性别</th>
        <th>邮箱</th>
        <th>手机号码</th>
      </tr>
      </thead>
      <tbody>
      <!-- row 1 -->
      <tr v-for="student in useUserStore().users?.records" :key="student.id">
        <th>
          <label>
            <input type="checkbox" class="checkbox" v-model="selectedIds" :value="student.id">
          </label>
        </th>
        <td>{{student.username}}</td>
        <td>{{student.realName}}</td>
        <td>{{student.gender}}</td>
        <td>{{student.email}}</td>
        <td>{{student.phone}}</td>
        <th class="flex gap-2">
          <user-editor :user="student">编辑</user-editor>
          <!--          <button class="btn btn-accent btn-xs">编辑</button>-->
          <button class="btn btn-error btn-xs" @click="deleteUser(student.username)">删除</button>
        </th>
      </tr>
      </tbody>
    </table>
    <button :class="['btn btn-error btn-md',{'hidden':!selectAll}]" >全部删除</button>
  </div>
  <pagination :data="useUserStore().users" @page-change="handlePageChange"></pagination>
</template>

<style scoped>

</style>